from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.db.models import Q
from ..models import CharacterTemplate

class TemplateListView(LoginRequiredMixin, ListView):
    """角色模板列表"""
    model = CharacterTemplate
    template_name = 'battle/template/list.html'
    context_object_name = 'templates'
    paginate_by = 10
    
    def get_queryset(self):
        queryset = CharacterTemplate.objects.filter(
            Q(creator=self.request.user) |  # 创建的模板
            Q(is_public=True) |  # 公开模板
            Q(allowed_users=self.request.user)  # 被授权的模板
        ).distinct()
        
        # 搜索过滤
        search = self.request.GET.get('search', '')
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) |
                Q(description__icontains=search) |
                Q(tags__icontains=search)
            )
            
        # 类型过滤
        template_type = self.request.GET.get('type', '')
        if template_type:
            queryset = queryset.filter(template_type=template_type)
            
        return queryset.order_by('-created_at')

class TemplateCreateView(LoginRequiredMixin, CreateView):
    """创建角色模板"""
    model = CharacterTemplate
    template_name = 'battle/template/form.html'
    fields = ['name', 'description', 'template_type', 'is_public', 'tags', 'template_data']
    success_url = reverse_lazy('battle:template_list')
    
    def form_valid(self, form):
        form.instance.creator = self.request.user
        return super().form_valid(form)

class TemplateUpdateView(LoginRequiredMixin, UpdateView):
    """更新角色模板"""
    model = CharacterTemplate
    template_name = 'battle/template/form.html'
    fields = ['name', 'description', 'template_type', 'is_public', 'tags', 'template_data']
    success_url = reverse_lazy('battle:template_list')
    
    def get_queryset(self):
        return CharacterTemplate.objects.filter(creator=self.request.user)

class TemplateDeleteView(LoginRequiredMixin, DeleteView):
    """删除角色模板"""
    model = CharacterTemplate
    success_url = reverse_lazy('battle:template_list')
    
    def get_queryset(self):
        return CharacterTemplate.objects.filter(creator=self.request.user)
